package com.wetool.controller;

import java.security.Principal;
import java.util.List;
import javax.validation.Valid;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.EntityLinks;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.wetool.entity.Commodity;
import com.wetool.entity.PublicCommodity;
import com.wetool.exception.CommodityNotFindException;
import com.wetool.exception.MerchantNotLoginException;
import com.wetool.model.PublicCommodityAdd;
import com.wetool.model.CommodityQuery;
import com.wetool.model.Message;
import com.wetool.model.Message.Result;
import com.wetool.service.commodity.PublicCommodityService;
import com.wetool.model.SearchParam;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

/**
 * 商家库(公共库)控制
 */
@RestController
@RequestMapping("/public/commodity/")
@RefreshScope
@Api(description = "商品管理(公共库)")
public class PublicCommodityController {
	private static final Logger logger = LogManager.getLogger(PublicCommodityController.class); 
	
	@Autowired
	private PublicCommodityService publicCommodityService;

	@Autowired
	private EntityLinks entityLinks;


	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ResponseEntity<?> list(SearchParam searchParam, Pageable p,
			final PagedResourcesAssembler<PublicCommodity> assembler) throws CommodityNotFindException {
		if (searchParam.getCategoryId() == null) {
			searchParam.setCategoryId(1L);
		}
		Page<PublicCommodity> adverts = publicCommodityService.find(searchParam, p);
		return new ResponseEntity<>(new Message<>(Result.SUCCESS, assembler.toResource(adverts)), HttpStatus.OK);
	}
	
	@ApiOperation(value="多条件查询商品列表(公共库)", notes="多条件查询公共库的商品列表", response = Message.class)
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "page", value = "第几页", required = false, dataType = "int", paramType = "query", defaultValue = "0"),
    	@ApiImplicitParam(name = "size", value = "每页行数", required = false, dataType = "int", paramType = "query", defaultValue = "20"),
    	@ApiImplicitParam(name = "key", value = "查询条件（商品名称/条码/拼音）", required = false, dataType = "String", paramType = "path", defaultValue = "690"),
    	@ApiImplicitParam(name = "sort", value = "排序规则", required = false, dataType = "String", paramType = "query", defaultValue = "createTime,asc")
    })
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 12,message = "商家未登录!")
	})
	@RequestMapping(value = "/getByKey/{key}", method = RequestMethod.GET)
	public ResponseEntity<?> getByKey(@PathVariable String key, Pageable p,
			final PagedResourcesAssembler<PublicCommodity> assembler) throws CommodityNotFindException {
		SearchParam searchParam = new SearchParam();
		searchParam.setKey(key);
		Page<PublicCommodity> adverts = publicCommodityService.find(searchParam, p);
		return new ResponseEntity<>(new Message<>(Result.SUCCESS, assembler.toResource(adverts)), HttpStatus.OK);
	}
	
	@ApiOperation(value="提供扫码查询商品信息", notes="提供扫码查询商品信息",response = Message.class)
	@ApiImplicitParams({
		@ApiImplicitParam(name = "key", value = "商品条码", required = true,paramType = "path", dataType = "String",defaultValue = "6901294130036"),
		@ApiImplicitParam(name = "merchantId", value = "商家ID", required = true,paramType = "query", dataType = "Long")
	})
	@ApiResponses(value = {
			@ApiResponse(code = 0, message = "操作成功！"),
			@ApiResponse(code = 1, message = "操作失败！"),
			@ApiResponse(code = 5,message = "商品信息不存在!"),
			@ApiResponse(code = 8,message = "参数不正确！")
	})
	@RequestMapping(value = "/findByBorcode/{key}", method = RequestMethod.GET)
	public ResponseEntity<?> findByBorcode(Principal principal,Long merchantId,@PathVariable String key) throws Exception {
		logger.info("进入接口>提供扫码查询商品信息 . 参数 条码【{}】,商家ID【{}】", key , merchantId);
		if (merchantId == null) {
			throw new MerchantNotLoginException();
		}
		List<CommodityQuery> commoditys = publicCommodityService.findByBarcode(key);
		logger.info("结束接口>提供扫码查询商品信息 . 结果 商品信息集合【{}】", commoditys);
		return new ResponseEntity<Object>(new Message<>(Result.SUCCESS, commoditys), HttpStatus.OK);
	}
	
	@RequestMapping(value = "/find/{start}/{end}", method = RequestMethod.GET)
	public List<PublicCommodity> findAll(@PathVariable("start") Long start, @PathVariable("end") Long end) {
		List<PublicCommodity> c = publicCommodityService.findByIdBetween(start, end);
		return c;
	}
	
	@RequestMapping(method = RequestMethod.GET)
	public ResponseEntity<?> find(Pageable p, final PagedResourcesAssembler<PublicCommodity> assembler)
			throws CommodityNotFindException {
		SearchParam params = new SearchParam();
		params.setCategoryId(1L);
		Page<PublicCommodity> adverts = publicCommodityService.find(p);
		return new ResponseEntity<>(new Message<>(Result.SUCCESS, assembler.toResource(adverts)), HttpStatus.OK);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public ResponseEntity<?> findOne(@PathVariable Long id) {
		PublicCommodity commodity = publicCommodityService.findOne(id);
		return new ResponseEntity<Object>(new Message<>(Result.SUCCESS, commodity), HttpStatus.OK);
	}

	@RequestMapping(method = RequestMethod.POST)
	public ResponseEntity<?> create(Principal principal, @Valid @RequestBody PublicCommodityAdd commodity)
			throws Exception {
		// User user =
		// userService.findByUsername(principal.getName()).orElseThrow(AccessDeniedException::new);
		publicCommodityService.save(commodity);
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.setLocation(entityLinks.linkForSingleResource(Commodity.class, commodity).toUri());
		return new ResponseEntity<Object>(new Message<>(Result.SUCCESS, responseHeaders), HttpStatus.CREATED);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PATCH)
	public ResponseEntity<?> update(@PathVariable String id, @Valid @RequestBody PublicCommodityAdd commodity)
			throws Exception {
		PublicCommodity co = publicCommodityService.save(commodity);
		return new ResponseEntity<Object>(new Message<>(Result.SUCCESS, co), HttpStatus.OK);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public ResponseEntity<?> delete(@PathVariable Long id) {
		publicCommodityService.delete(id);
		return new ResponseEntity<Object>(new Message<>(Result.SUCCESS), HttpStatus.NO_CONTENT);
	}
}
